package com.abbas.abchat.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.abbas.abchat.AbChatApplication;
import com.abbas.abchat.R;
import com.abbas.abchat.adapter.ChatListAdapter;
import com.abbas.abchat.dao.ChatMsgDao;
import com.abbas.abchat.dao.ChatTableDao;
import com.abbas.abchat.dao.impl.ChatMsgDaoImpl;
import com.abbas.abchat.dao.impl.ChatTableDaoImpl;
import com.abbas.abchat.entity.Account;
import com.abbas.abchat.entity.ChatMsg;
import com.abbas.abchat.entity.ChatTable;
import com.abbas.abchat.utils.SpUtils;
import com.abbas.abchat.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ChatActivity extends BaseActivity implements View.OnClickListener{

    //当前两者共有的数据库名
    private String dbName = null;
    //当前对话者ID
    private Account account = null;

    private ImageButton ibBack;
    private ImageButton ibMore;
    private TextView title;
    private ListView lv;
    private LinearLayout linearLayout;
    private ImageButton voice;
    private EditText et;
    private ImageButton add;

    //自动回复Handler的msg标识ID
    private final int AUTO_REPLAY_CODE = 0x02135;

    //所有聊天记录
    private List<ChatMsg> allChatMsg = null;
    private ChatListAdapter chatListAdapter;

    //聊天数据库dao
    private ChatMsgDao chatMsgDao;

    //自动回复关键字
    private Map<String, String> replays;

    public final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //当前账号ID
    private int id = AbChatApplication.getAccount().getId();

    private String lastContent;
    private String lastTime;


    //是否发送过消息
//    private boolean isSendMsgBefore = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat;
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case AUTO_REPLAY_CODE:
                    autoReplay(replays.get((String) msg.obj));
                    getData();
                    saveLastData();
                    break;
            }
        }
    };

    @Override
    protected void init() {
        //get the chat db name
        dbName = getIntent().getStringExtra("dbName");
        account = (Account) getIntent().getSerializableExtra("account");
        //TODO: If the database does not exist or the data transfer is wrong,need send a message
        if (!TextUtils.isEmpty(dbName)){
            chatMsgDao = new ChatMsgDaoImpl(this,dbName);

            try {
                allChatMsg = chatMsgDao.findAll();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            showMessage(getString(R.string.unknown_error));
        }

        ibMore = findViewById(R.id.im_more);
        ibBack = (ImageButton) findViewById(R.id.ib_back);
        title = (TextView) findViewById(R.id.title);
        lv = (ListView) findViewById(R.id.lv_chat);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        voice = (ImageButton) findViewById(R.id.voice);
        et = (EditText) findViewById(R.id.et);
        add = (ImageButton) findViewById(R.id.add);

        if (account != null){
            if (TextUtils.isEmpty(account.getName())){
                title.setText(account.getAccount());
            }else {
                title.setText(account.getName());
            }

            if (!TextUtils.isEmpty(String.valueOf(account.getId()))){
                SpUtils spUtils = SpUtils.config(this,"s"+account.getId());
                replays = spUtils.getAll();
            }
        }else {
            showMessage(getString(R.string.unknown_error));
        }

        if (allChatMsg != null && allChatMsg.size() != 0){
            chatListAdapter = new ChatListAdapter(this,allChatMsg,AbChatApplication.getAccount(),account,dbName);
            lv.setAdapter(chatListAdapter);

            lastContent = allChatMsg.get(allChatMsg.size()-1).getContent();
            lastTime = allChatMsg.get(allChatMsg.size()-1).getDate();
        }else {
            showMessage(getString(R.string.unknown_error));
        }

        ibMore.setOnClickListener(this);
        ibBack.setOnClickListener(this);
    }

    @Override
    protected void initEvent() {
        et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND){
                    //若成功插入数据
                    if (sendMessage()){
                        //清空et
                        et.setText("");
                        //刷新list数据
                        getData();
                        //保存最终数据
                        saveLastData();
                    }
                }
                return true;
            }
        });
    }

    //校验数据准确性，生成时间戳操作
    private boolean sendMessage(){
        String msg = et.getText().toString().trim();
        //校验数据正确性
        if (!TextUtils.isEmpty(msg)){
            //当前发生会话的时间与上一次会话的时间是否超过3分钟
            if (TimeUtils.getInstance(lastTime).overThreeMin()){
                //TODO: 创建时间戳
                ChatMsg chatMsg = new ChatMsg();
                chatMsg.setDate(simpleDateFormat.format(new Date()));
                chatMsg.setType(1);

                try {
                    long insertResult = chatMsgDao.insert(chatMsg);
                    if (insertResult <= 0){
                        showMessage(getString(R.string.database_error));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return initMessage(msg);


        }else {
            //TODO: 提示用户输入非空数据
        }
        return true;
    }

    //实际数据插入方法
    private boolean initMessage(String msg){
        String time = simpleDateFormat.format(new Date());
        //若为时间戳 无id
        ChatMsg chatMsg = new ChatMsg();

        chatMsg.setContent(msg);
        chatMsg.setpId(id);
        chatMsg.setDate(time);

        long result = -1;

        try {
            result = chatMsgDao.insert(chatMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result < 0){
            showMessage(getString(R.string.database_error));
            return false;
        }else {
            lastContent = msg;
            lastTime = time;

            if (replays.containsKey(msg)){
                Message message = mHandler.obtainMessage();
                message.what = AUTO_REPLAY_CODE;
                message.obj = msg;
                mHandler.sendMessageDelayed(message,800);
            }
        }
        return true;
    }

    //自动回复调用
    private boolean autoReplay(String s) {
        String time = simpleDateFormat.format(new Date());
        //无需检查数据正确性
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setpId(account.getId());
        chatMsg.setDate(time);
        chatMsg.setContent(s);

        long insertResult = -1;

        try {
            insertResult = chatMsgDao.insert(chatMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (insertResult < 0){
            showMessage("数据库错误");
            return false;
        }
        lastContent = s;
        lastTime = time;
        return true;
    }

    private void saveLastData() {

        Account LA = AbChatApplication.getAccount();
        Account PA = account;

        ChatTableDao LADao = new ChatTableDaoImpl(this, LA.getChatTableDbName());
        ChatTableDao PADao = new ChatTableDaoImpl(this,PA.getChatTableDbName());


        ChatTable chatTable = new ChatTable();
        chatTable.setPeopleId(PA.getId());
        chatTable.setLastContent(lastContent);
        chatTable.setLastTime(lastTime);
        try {
            int result1 = LADao.updateByPid(chatTable);
            if (result1 > 0){
                Log.i("LADao.updateByPid(chatTable)", "onDestroy: ");
            }else {
                Log.e("LADao.updateByPid(chatTable)", "onDestroy: ");
                showMessage(getString(R.string.database_error));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        chatTable.setPeopleId(LA.getId());
        try {
            int result2 = PADao.updateByPid(chatTable);
            if (result2 > 0){
                Log.i("LADao.updateByPid(chatTable)", "onDestroy: ");
            }else {
                Log.e("LADao.updateByPid(chatTable)", "onDestroy: ");
                showMessage(getString(R.string.database_error));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getData(){
        try {
            allChatMsg = chatMsgDao.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

        chatListAdapter.setMsg(allChatMsg);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(String.valueOf(account.getId()))){
            SpUtils spUtils = SpUtils.config(this,"s"+account.getId());
            replays = spUtils.getAll();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.im_more:
                Intent intent = new Intent(ChatActivity.this,SetReplayActivity.class);
                intent.putExtra("account",account);
                startActivity(intent);
                break;
            case R.id.ib_back:
                finishThis();
                break;
        }
    }
}